package com.lyl.mallcloud.config;


import com.lyl.mallcloud.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class AuthHandlerInterceptor implements HandlerInterceptor {

    public static final String SEC="liyunlong";
    private final StringRedisTemplate stringRedisTemplate;

    @Autowired
    public AuthHandlerInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(@NotNull HttpServletRequest httpServletRequest,
                             @NotNull HttpServletResponse httpServletResponse,
                             @NotNull Object object){
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        String token = httpServletRequest.getHeader("Authorization");
        if (null == token || "".equals(token.trim())) {
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        Map<String, Object> map = JwtUtil.parseJWT(SEC, token);
        Integer userId = (Integer) map.get("userId");
        String token2 = stringRedisTemplate.opsForValue().get("token:" + userId);
        if (!token.equals(token2)) {
            log.info("token已过期");
          httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
          return false;
        }
        stringRedisTemplate.opsForValue().set("token:"+userId,token,30, TimeUnit.MINUTES);
        return true;
    }
}